<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use Redirect, Input, Response;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;
use App\Models\Attachs;


class UploadController extends Controller
{
     public function uploadImg(){
            $file = Input::file('file');
            $disk = QiniuStorage::disk('qiniu');
            
            if($file){
                $allowed_extensions = ["png", "jpg", "gif"];
                if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg or gif.'];
                }
                $imagesName=  file_get_contents($file->getRealPath());
                
                $file_name=$this->check(md5($file->getClientOriginalName().time()), $file->getClientOriginalExtension());
                $disk->put($file_name, $imagesName);
                $attach_data=array(
                    'name'=>$file_name,
                    'path'=>$disk->imagePreviewUrl($file_name,''),
                    'exts'=>$file->getClientOriginalExtension(),
                    'addtime'=>time(),
                );
                $attach =Attachs::create($attach_data);
                return Response::json(array('success' =>true,'url' =>$disk->imagePreviewUrl($file_name,''),'id' => $attach->id) );
           }elseif(Input::get('base64')){
               $image_base64 = Input::get('base64');
               $file_names = Input::get('filename');
               $image_base64 = str_replace('data:image/jpeg;base64,', '', $image_base64);
               $file=base64_decode($image_base64);
               $file_arr = explode('.', $file_names);
               $ext = end($file_arr);
               $file_name=$this->check(md5($file_names.time()),$ext);
               $disk->put($file_name,$file);
               $attach_data=array(
                   'name'=>$file_name,
                   'path'=>$disk->imagePreviewUrl($file_name,''),
                   'exts'=>$ext,
                   'addtime'=>time(),
               );
               $attach =Attachs::create($attach_data);
               return Response::json(array('success'=>true,'url'=>$disk->imagePreviewUrl($file_name,''),'id' => $attach->id));
           }else {
               return Response::json(array('success'=>false));
           }
        }
    
        public function check($name,$ext){
            $disk = QiniuStorage::disk('qiniu');
            if($disk->exists($name.'.'.$ext)){
                $name=md5($name.time());
                $this->check($name,$ext);
            }
            return $name.'.'.$ext;
        }
}
